package com.toprs.base.service

import com.toprs.base.entity.Dept
import com.toprs.base.entity.DeptManager
import com.toprs.base.exception.CustomException
import com.toprs.base.mapper.*
import org.springframework.stereotype.Service
import com.toprs.base.mapper.DeptDynamicSqlSupport.order
import com.toprs.base.mapper.DeptManagerDynamicSqlSupport.deptId

@Service
class DeptService(val deptMapper: DeptMapper, val deptManagerMapper: DeptManagerMapper) {

    fun addDept(dept: Dept) {
        deptMapper.insert(dept)
    }


    private fun setDeptChildren(allList: MutableList<Dept>, id: Int): List<Dept> {

        val list = allList.filter { it.parentId == id }

        allList.removeAll(list)
        for (dept in list) {
            dept.children = setDeptChildren(allList, dept.id!!)
        }
        return list
    }


    fun getDeptList(): List<Dept> {
        val allList = deptMapper.select {
            orderBy(order)
        }
        return setDeptChildren(allList.toMutableList(), 1)
    }

    fun deleteDept(id: Int) {
        deptMapper.deleteByPrimaryKey(id)
    }

    fun editDept(dept: Dept) {
        if (dept.id != null) {
            deptMapper.updateByPrimaryKey(dept)
        } else {
            throw CustomException("部门ID不能为空！")
        }
    }

    fun setManager(deptManager: DeptManager) {

        deptManagerMapper.delete {
            where {
                deptId.isEqualTo(deptManager.deptId!!)
            }
        }
        deptManagerMapper.insert(deptManager)
    }
}